import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisDemoZSet {

    public static void test1(Jedis jedis) {
        System.out.println("zadd 和 zrange");
        jedis.flushAll();

        long result = jedis.zadd("key", 1, "1");
        Map<String, Double> map = new HashMap<>();
        map.put("2", 2.0);
        map.put("3", 3.0);
        result = jedis.zadd("key", map);

        List<String> members = jedis.zrange("key", 0, -1);
        System.out.println(members);

        List<Tuple> membersWithScores = jedis.zrangeWithScores("key", 0, -1);
        System.out.println(membersWithScores);
        String element = membersWithScores.get(0).getElement();
        double score = membersWithScores.get(0).getScore();
        System.out.println(element + ":" + score);
    }

    public static void test2(Jedis jedis) {
        System.out.println("zcard");
        jedis.flushAll();

        jedis.zadd("key", 1, "1");
        jedis.zadd("key", 2, "2");
        jedis.zadd("key", 3, "3");

        long result = jedis.zcard("key");
        System.out.println("result: " + result);
    }

    public static void test3(Jedis jedis) {
        System.out.println("zrem");
        jedis.flushAll();

        jedis.zadd("key", 1, "1");
        jedis.zadd("key", 2, "2");
        jedis.zadd("key", 3, "3");

        long result = jedis.zrem("key", "1");
        System.out.println("result: " + result);

        List<Tuple> values = jedis.zrangeWithScores("key", 0, -1);
        System.out.println("values: " + values);
    }

    public static void test4(Jedis jedis) {
        System.out.println("zscore");
        jedis.flushAll();

        jedis.zadd("key", 1, "1");
        jedis.zadd("key", 2, "2");
        jedis.zadd("key", 3, "3");

        double score = jedis.zscore("key", "1");
        System.out.println("score: " + score);
    }

    public static void test5(Jedis jedis) {
        System.out.println("zrank");
        jedis.flushAll();

        jedis.zadd("key", 1, "1");
        jedis.zadd("key", 2, "2");
        jedis.zadd("key", 3, "3");

        //获取下标
        Long rank = jedis.zrank("key", "2");
        System.out.println("rank: " + rank);
    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:6666");

        try (Jedis jedis = jedisPool.getResource()) {
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
//            test4(jedis);
            test5(jedis);
        }
    }
}
